<?php
function connectDB(){
    $dsn = 'mysql:dbname=Library;host=localhost';
    $user = 'root';
    $password = '123456';
    $db = new PDO($dsn, $user, $password);
    return $db;
}

/**
 * 判断读者库中是否有该用户
 * @param $userid
 * @return bool
 */
function hasUser($userid){
    $db=connectDB();
    $statement = $db->prepare('select * from Users where ID=:ID');
    $statement->execute([':ID' => $userid]);
    if(!$statement->fetch())
        return false;
    return true;
}

/**
 * 判断数据库中Book表中是否有该书
 * @param $bookid
 * @return bool
 */
function hasBook($bookid){
    $db=connectDB();
    $statement = $db->prepare('select * from Book where ID=:ID');
    $statement->execute([':ID' => $bookid]);
    if(!$statement->fetch())
        return false;
    return true;
}

/**
 * 判断该书是否在库未借出的书
 * @param $bookid
 * @return bool
 */
function effectBook($bookid){
    $db=connectDB();
    if(!hasBook($bookid)) return false;

    $statement2=$db->prepare('select Status from Book where ID=:ID');
    $statement2->execute([':ID' => $bookid]);
    if(!((bool)($statement2->fetch(PDO::FETCH_ASSOC)['Status'])))
        return false;
    return true;
}

/**
 * 判断该书是否在库未归还的书
 * @param $bookid
 * @return bool
 */
function effectBook2($bookid){
    $db=connectDB();
    if(!hasBook($bookid)) return false;

    $statement2=$db->prepare('select Status from Book where ID=:ID');
    $statement2->execute([':ID' => $bookid]);
    if((bool)($statement2->fetch(PDO::FETCH_ASSOC)['Status']))
        return false;
    return true;
}


/**
 * 往数据库添加借书记录
 * @param $userid
 * @param $bookid
 */
function addRecord($userid,$bookid){
    $db=connectDB();
    $statement = $db->prepare('insert into Record (User,Book,BorrowTime,Status) VALUES (:User,:Book,:Time,:Status)');
    $statement->execute([':User' => $userid,':Book'=>$bookid,':Time'=>date('Y-m-d'),':Status'=>'0']);
}



function updateBookStatus($bookid,$flag){
    $db=connectDB();
    $statement = $db->prepare('update Book set Status=:flag where ID=:ID');
    $statement->execute([':flag'=>$flag,':ID'=>$bookid]);
}

function updateRecordStatus($bookid,$flag){
    $db=connectDB();
    $statement = $db->prepare('update Record set Status=:flag where Book=:ID');
    $statement->execute([':flag'=>$flag,':ID'=>$bookid]);
}

/**
 * 查询用户还没有归还的书
 */
function UserBorrow($userid){
    $db=connectDB();
    $statement = $db->prepare('select Record.User as UserID,Users.Name as UserName,Record.Book as BookID,Book.Name as BookName,Record.BorrowTime as BorrowTime,Record.ReturnTime as ReturnTime,Record.Status from Record,Book,Users where Record.User=:User and Record.User=Users.ID and Record.Book=Book.ID and Record.Status=:status');
    $statement->execute([':User'=>$userid,':status'=>'0']);
    $result=$statement->fetchAll(PDO::FETCH_ASSOC);
    return $result;
}